//
//  WmcPresentBackControl.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/22.
//

import UIKit
import YPBedrock

class WmcPresentBackControl: UIControl {
    lazy var maskLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.fillRule = .evenOdd
        return layer
    }()

    /// 镂空区域
    var hollowRects: [WmcPresentVC.Config.HollowRect] = []
    /// 透传回调
    var hitPassthroughBlock: YPBlock.OneParam<WmcPresentVC.Config.HollowRect>?
    /// 消失回调
    var hitTestDismissBlock: YPBlock.OneParam<WmcPresentVC.Config.HollowRect>?
    
    override func layoutSubviews() {
        super.layoutSubviews()

        if !hollowRects.isEmpty {
            createHollowRects()
            maskLayer.frame = bounds
            layer.mask = maskLayer
        }
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let superV = super.hitTest(point, with: event)
        for hollowRect in hollowRects {
            let rect = hollowRect.rect
            if rect.contains(point) { // 点击到触发区域
                if hollowRect.isHitPassthrough { // 要求透传
                    hitPassthroughBlock?(hollowRect)
                    if hollowRect.isHitPassthroughAutoDismiss { // 要求透传后dismiss
                        hitTestDismissBlock?(hollowRect)
                    }
                    return nil
                }
            }
        }
        return superV
    }

    /// 创建镂空区域
    func createHollowRects() {
        guard !hollowRects.isEmpty else { return }
        // 提前准备外框路径
        let framePath = UIBezierPath(rect: bounds)
        // 拿出当前的数据
        for hollowRect in hollowRects { // 创建该引导的路径
            if hollowRect.isHollow { // 要展示出来
                let hollowPath = UIBezierPath(roundedRect: hollowRect.rect,
                                              byRoundingCorners: hollowRect.roundingCorners,
                                              cornerRadii: hollowRect.cornerRadii.yp.cgSize)
                framePath.append(hollowPath)
            }
        }
        maskLayer.path = framePath.cgPath
    }
}
